package com.fingard.dsp.bank.directbank.boc22;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsAPI;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.TcpPortClient;

import java.io.File;

/**
 * 中国银行CSPB直连(BOC22)批量代收付
 */
public class BOC22BatPayRec extends BOC22Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        TcpPortClient tmpClient = null;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqBat.ownAct, "");
            if (actItem == null) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号" + p_reqBat.ownAct + "的批量商户配置节点";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            String tmpBatType = "";
            if ("1988".equals(p_reqBat.reqHeader.transType)) {
                if ("198801".equals(p_reqBat.reqHeader.commandCode)) {
                    tmpBatType = "C1";
                } else if ("198802".equals(p_reqBat.reqHeader.commandCode)) {
                    tmpBatType = "C2";
                } else if ("198803".equals(p_reqBat.reqHeader.commandCode)) {
                    tmpBatType = "C3";
                }
            } else if ("9188".equals(p_reqBat.reqHeader.transType)) {
                if ("918801".equals(p_reqBat.reqHeader.commandCode)) {
                    tmpBatType = "D1";
                } else if ("918802".equals(p_reqBat.reqHeader.commandCode)) {
                    tmpBatType = "D2";
                }
            }
            String tmpUploadFileName = actItem.merchantId + "-" + tmpBatType + "-" + Format.Date8Format.format(p_reqBat.getPayDateTime()) + "-V00" + p_reqBat.reqBatchNO + "-" + bankFront.org + ".DAT";

            StringBuilder sbFileContent = new StringBuilder();

            //客户端交易请求报文
            StringBuilder trHead = new StringBuilder();
            String tmpStrHead = "";
            trHead.append("300002");
            trHead.append(Format.Date8Format.format(p_reqBat.getPayDateOnly()));
            trHead.append(String.format("%-50s", tmpUploadFileName));
            trHead.append("999999");
            tmpStrHead = trHead.toString();
            WriteBankLogLn("客户端交易请求报文:" + tmpStrHead);
            // 代收付文件内容

            /* CSPB直连业务类型：C1 - 行内代付，C2 - 跨行代付(小额定期贷记），C3 - 跨行代付(普通贷记)，D1 - 行内代收 ，D2 - 跨行代收(小额定期借记)*/
            sbFileContent.append(tmpBatType);

            /* 批次号(与文件名中批次号的后3位保持一致) */
            sbFileContent.append(p_reqBat.reqBatchNO.substring(p_reqBat.reqBatchNO.length() - 3));

            /* 保险公司收款账号或付款账号 */
            sbFileContent.append(String.format("%-25s", p_reqBat.ownAct));

            /* 总金额 */
            sbFileContent.append(String.format("%16s", p_reqBat.totalAmt).replace(" ", "0"));

            /* 总笔数 */
            sbFileContent.append(String.format("%12s", p_reqBat.totalNum).replace(" ", "0"));

            /* 业务摘要 */
            sbFileContent.append(convertBusType(tmpBatType));

            /* 币种 */
            sbFileContent.append("CNY");

            /* 加密标识 */
            sbFileContent.append("00");

            /* 文本版本号 */
            sbFileContent.append("00000001");

            /* 汇划流水号 */
            sbFileContent.append(String.format("%-32s", ""));

            /* 汇划日期 */
            sbFileContent.append(String.format("%-8s", ""));

            /* 退划流水号 */
            sbFileContent.append(String.format("%-32s", ""));

            /* 退划日期 */
            sbFileContent.append(String.format("%-8s", ""));

            /* 结束标识 */
            sbFileContent.append("|\n");

            // 文件明细
            while (p_reqBat.readRecord()) {
                StringBuilder tmpReqBodyDetail = new StringBuilder();

                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    oppName = p_reqBat.readedDetail.payName;
                }

                /* 账号 */
                tmpReqBodyDetail.append(String.format("%-25s", oppAct));

                /* 账号名称 */
                tmpReqBodyDetail.append(CfbsAPI.rightFill(oppName, 58, " "));

                /* 金额 */
                tmpReqBodyDetail.append(String.format("%16s", p_reqBat.readedDetail.payAmount).replace(" ", "0"));

                /* 省行标识 */
                tmpReqBodyDetail.append(String.format("%-14s", p_reqBat.readedDetail.ownBankCode));

                if(getBankConfig().getValueAsBool("setCertEmpty")){
                    /* 证件类型 */
                    tmpReqBodyDetail.append(String.format("%-2s", ""));
                    /* 证件号码 */
                    tmpReqBodyDetail.append(String.format("%-32s", ""));
                }else{
                    /* 证件类型 */
                    tmpReqBodyDetail.append(String.format("%-2s", convertCertTypeToBank(p_reqBat.readedDetail.certType)));
                    /* 证件号码 */
                    tmpReqBodyDetail.append(String.format("%-32s", p_reqBat.readedDetail.certNum));
                }

                /* 备注 */
                tmpReqBodyDetail.append(String.format("%-80s", CfbsAPI.rightFill(p_reqBat.readedDetail.memo, 58, " ")));

                if ("C1".equals(tmpBatType)) {
                    /* 空域 */
                    tmpReqBodyDetail.append(String.format("%-220s", ""));

                    /* 冲正状态 */
                    tmpReqBodyDetail.append(String.format("%-1s", ""));

                    /* 冲正交易核心返回码 */
                    tmpReqBodyDetail.append(String.format("%-8s", ""));

                    /* 冲正交易核心返回信息 */
                    tmpReqBodyDetail.append(String.format("%-80s", ""));

                    /* 空域 */
                    tmpReqBodyDetail.append(String.format("%-11s", ""));

                    /* 上送报文结束标识 */
                    tmpReqBodyDetail.append("|");

                    /* 返回结果 */
                    tmpReqBodyDetail.append(String.format("%-1s", ""));

                    /* 返回码 */
                    tmpReqBodyDetail.append(String.format("%-8s", ""));

                    /* 返回信息 */
                    tmpReqBodyDetail.append(String.format("%-150s", ""));
                } else {
                    /* 空域 */
                    tmpReqBodyDetail.append(String.format("%-140s", ""));

                    /* 实扣金额 */
                    tmpReqBodyDetail.append(String.format("%-16s", ""));

                    /* 空域 */
                    tmpReqBodyDetail.append(String.format("%-64s", ""));

                    /* 冲正状态 */
                    tmpReqBodyDetail.append(String.format("%-1s", ""));

                    /* 冲正交易核心返回码 */
                    tmpReqBodyDetail.append(String.format("%-8s", ""));

                    /* 冲正交易核心返回信息 */
                    tmpReqBodyDetail.append(String.format("%-80s", ""));

                    /* 空域 */
                    tmpReqBodyDetail.append(String.format("%-11s", ""));

                    /* 上送报文结束标识 */
                    tmpReqBodyDetail.append("|");

                    /* 返回结果 */
                    tmpReqBodyDetail.append(String.format("%-1s", ""));

                    /* 返回码 */
                    tmpReqBodyDetail.append(String.format("%-8s", ""));

                    /* 返回信息 */
                    tmpReqBodyDetail.append(String.format("%-150s", ""));

                }
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次请求文件内容:\r\n" + sbFileContent.toString());

            if (p_reqBat.reqBatchNO.length() > 8) {
                retAts.respCode = "0";
                retAts.respInfo = "批次号长度应该为8位,实际长度为:" + p_reqBat.reqBatchNO.length() + ",请设置'流水号长度'银行参数!";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次请求文件保存本机路径: " + tmpLocalMarkPath);

            String localFilepath = createTempFileDirectory() + File.separator + p_reqBat.reqBatchNO + ".txt";
            FileHelper.writeFile(localFilepath, tmpUploadFileName, getCharset());
            WriteBankLogLn("文件名保存本地路径：" + localFilepath);

            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件[" + tmpLocalMarkPath + "]已上传,请勿重复上传!";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            String sbFileStr = sbFileContent.toString();
            File tmpLocalFile = new File(tmpLocalMarkPath);
            if (!tmpLocalFile.exists()) {
                tmpLocalFile.createNewFile();
            }
            FileHelper.writeFile(tmpLocalMarkPath, sbFileStr, getCharset());

            tmpClient = new TcpPortClient(bankFront.serverIP, Integer.valueOf(bankFront.serverPort), this);

            int tmpMaxBufferSize = 0;

            byte[] tmpContentBytes = sbFileStr.getBytes(getCharset());
            int tmpToSendLen = tmpContentBytes.length;
            int tmpTimeCount = -1;
            int tmpStep = 1;
            int tmpLastSeq = -1;
            int tmpEachBufferSize = 0;
            boolean tmpFinished = false;
            String tmpBankAskSeq = "";// 数据包序号
            String tmpFileInfoCode = "";
            String tmpFileMsg = "";

            String[] tmpBkRet = new String[]{"", ""};
            while (tmpToSendLen > 0) {
                if (tmpStep == 1) {
                    /* 1.客户端交易请求 */
                    tmpBkRet = sendToBank(tmpStrHead, tmpClient);
                    tmpStep ++;
                    tmpTimeCount = 0;
                } else {
                    tmpMaxBufferSize = 8192;
                    /*分段发送*/
                    WriteBankLogLn("tmpToSendLen: " + tmpToSendLen);
                    WriteBankLogLn("tmpMaxBufferSize: " + tmpMaxBufferSize);
                    if (tmpToSendLen > tmpMaxBufferSize) {
                        tmpEachBufferSize = tmpMaxBufferSize;
                    } else {
                        tmpEachBufferSize = tmpToSendLen;
                    }
                    WriteBankLogLn("tmpEachBufferSize: " + tmpEachBufferSize);
                    byte[] tmpBufferBytes = new byte[tmpEachBufferSize];
                    System.arraycopy(tmpContentBytes, tmpContentBytes.length - tmpToSendLen, tmpBufferBytes, 0, tmpEachBufferSize);
                    WriteBankLogLn2("当前报文体字节数:" + tmpBufferBytes.length);
                    tmpBkRet = sendToBank(tmpBufferBytes, tmpClient);
                    tmpTimeCount++;
                    tmpLastSeq = Integer.parseInt(tmpBankAskSeq);
                    tmpToSendLen -= tmpMaxBufferSize;
                }

                if (tmpBkRet[0].length() == 0) {
                    tmpBkRet[1] = tmpBkRet[1].substring(4 ,tmpBkRet[1].length());
                    byte[] bytesBkRet = tmpBkRet[1].getBytes(getCharset());
                    if (bytesBkRet.length > 5) {
                        String respRetCode = "R" + String.format("%5s", tmpTimeCount).replaceAll(" ", "0");
                        WriteBankLogLn("respRetCode：" + respRetCode);
                        WriteBankLogLn("tmpBkRet[1]：" + tmpBkRet[1]);
                        if (tmpBkRet[1].equals(respRetCode)) {
                            WriteBankLogLn("响应报文类型为【报文2】,请求包:" + tmpBkRet[1]);
                            tmpBankAskSeq = new String(bytesBkRet, 1, 5);
                            int tmpAskSeq = Integer.parseInt(tmpBankAskSeq);
                            WriteBankLogLn("【报文2】响应数据中数据包序号：" + tmpAskSeq);
                            int expectedSeq = tmpLastSeq + 1;
                            WriteBankLogLn("请求数据中数据包序号：" + expectedSeq);
                            if (tmpAskSeq == expectedSeq) {
                                WriteBankLogLn("继续读取文件------tmpToSendLen长度为：" + tmpToSendLen);
                                // 继续读取文件
                                if (tmpToSendLen > 0) {
                                    tmpFinished = false;
                                    WriteBankLogLn("tmpToSendLen长度为：" + tmpToSendLen);
                                } else {
                                    tmpFinished = true;
                                    tmpFileMsg = "数据包序号[" + tmpAskSeq + "]已无数据可读!";
                                    break;
                                }
                            } else {
                                tmpFinished = false;
                                tmpFileMsg = "数据包序号[" + tmpAskSeq + "]与预期序号[" + expectedSeq + "]不符!";
                                break;
                            }
                        } else {
                            WriteBankLogLn("无法识别的响应报文:\r\n" + tmpBkRet[1]);
                            WriteBankLogLn("3.【报文2】不能识别的应答类型：" + (char) bytesBkRet[tmpBkRet[1].length()]);
                            tmpFinished = false;
                            tmpFileMsg = "不能识别的应答类型：" + (char) bytesBkRet[tmpBkRet[1].length()];
                            break;
                        }
                    }
                } else {
                    tmpFinished = false;
                    tmpFileInfoCode = "E9999";
                    tmpFileMsg = tmpBkRet[1];
                    break;
                }
            }

            //5、发送方可以校验块号，决定是否继续发送。反复进行3、4步，直到发送方发送文件完毕，发送结束标志8个0x0(也是报文长度加报文000800000000,0为0x00)
            if (tmpFinished) {
                tmpBkRet = sendToBank("\0\0\0\0\0\0\0\0", tmpClient);
                if (tmpBkRet[0].length() == 0) {
                    if (tmpBkRet[1].length() == 74) {
                        retAts.respCode = "0";
                        String tmpRespCode = tmpBkRet[1].substring(68, tmpBkRet[1].length());
                        retAts.respInfo = tmpRespCode;
                        retAts.transState = tmpRespCode;
                        retAts.payInfoCode = tmpRespCode;
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "返回内容格式未知";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpBkRet[1];
                }
            } else {
                retAts.respCode = "0";
                retAts.respInfo = tmpFileMsg;
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = tmpFileInfoCode;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.toString();
            WriteBankLogLn(ex);
        } finally {
            if (tmpClient != null) {
                if (tmpClient.socket != null) {
                    tmpClient.socket.close();
                }
                if (tmpClient.tmpOutput != null) {
                    tmpClient.tmpOutput.close();
                }
                if (tmpClient.tmpInput != null) {
                    tmpClient.tmpInput.close();
                }
            }
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        TcpPortClient tmpClient = null;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQryBat.ownAct, "");
            if (actItem == null) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号" + p_reqQryBat.ownAct + "的批量商户配置节点";
                retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeAfterDetail();
                return retAts;
            }
            String tmpBatType = "";
            if ("1998".equals(p_reqQryBat.reqHeader.transType)) {
                if ("198801".equals(p_reqQryBat.reqHeader.commandCode)) {
                    tmpBatType = "C1";
                } else if ("198802".equals(p_reqQryBat.reqHeader.commandCode)) {
                    tmpBatType = "C2";
                } else if ("198803".equals(p_reqQryBat.reqHeader.commandCode)) {
                    tmpBatType = "C3";
                }
            } else if ("9198".equals(p_reqQryBat.reqHeader.transType)) {
                if ("918801".equals(p_reqQryBat.reqHeader.commandCode)) {
                    tmpBatType = "D1";
                } else if ("918802".equals(p_reqQryBat.reqHeader.commandCode)) {
                    tmpBatType = "D2";
                }
            }
            String tmpLocalMarkPath = getTempFileDirectory() + File.separator + p_reqQryBat.reqBatchNO + ".txt";
            WriteBankLogLn("文件名保存本地路径:" + tmpLocalMarkPath);
            String tmpDownFileName = actItem.merchantId + "-" + tmpBatType + "-" + Format.Date8Format.format(p_reqQryBat.getBgnDateTime()) + "-V00" + p_reqQryBat.reqBatchNO + "-" + bankFront.org + ".RET";
            //客户端交易请求报文
            StringBuilder trHead = new StringBuilder();
            trHead.append("300003");
            trHead.append(Format.Date8Format.format(p_reqQryBat.getBgnDateTime()));
            trHead.append(String.format("%-50s", tmpDownFileName));
            trHead.append("999999");
            String tmpStrHead = trHead.toString();
            WriteBankLogLn("客户端交易请求报文:" + tmpStrHead);
            System.out.println("客户端交易请求报文:" + tmpStrHead);
            tmpClient = new TcpPortClient(bankFront.serverIP, Integer.valueOf(bankFront.serverPort), this);
            /* 客户端交易请求 */

            byte[] tmpAllBytes = new byte[0];
            String tmpEachRecStr = "";
            String tmpStrEndFlag = "\0\0\0\0\0\0\0\0";
            boolean isContinue = true;
            int tmpCount = 0;
            String tmpStrRetCode = "";
            String[] tmpBkRet = sendToBank(tmpStrHead, tmpClient);
            if (tmpBkRet[0].length() == 0) {
                tmpBkRet[1] = tmpBkRet[1].substring(4, tmpBkRet[1].length());
                tmpAllBytes = tmpBkRet[1].getBytes(getCharset());
                if (tmpBkRet[1].length() == 70) {
                    tmpStrRetCode = tmpBkRet[1].substring(tmpBkRet[1].length() - 6, tmpBkRet[1].length());
                    if ("900001".equals(tmpStrRetCode) || "900008".equals(tmpStrRetCode)) {
                        WriteBankLogLn("tmpStrRetCode1="+ tmpStrRetCode);
                        retAts.respCode = "0";
                        retAts.payInfoCode = tmpStrRetCode;
                        if ("900001".equals(tmpStrRetCode)) {
                            WriteBankLogLn("tmpStrRetCode2="+ tmpStrRetCode);
                            retAts.transState = "900001";
                            retAts.respInfo = tmpStrRetCode + "-打开文件失败";
                        } else if ("900008".equals(tmpStrRetCode)) {
                            WriteBankLogLn("tmpStrRetCode3="+ tmpStrRetCode);
                            retAts.transState = "900008";
                            retAts.respInfo = tmpStrRetCode + "-服务端不能提供文件";
                        } else {
                            WriteBankLogLn("tmpStrRetCode4="+ tmpStrRetCode);
                            retAts.respInfo = tmpStrRetCode;
                        }
                        WriteBankLogLn("tmpStrRetCode5="+ tmpStrRetCode);
                        retAts.writeAfterDetail();
                        return retAts;
                    }
                }
                if (tmpBkRet[1].length() >= 8) {
                    tmpEachRecStr = tmpBkRet[1].substring(0, 8);
                }

                while (tmpEachRecStr != tmpStrEndFlag && isContinue) {
                    tmpCount++;
                    String tmpCountStr = "R" + String.format("%5s", tmpCount).replaceAll(" ", "0");
                    tmpBkRet = sendToBank(tmpCountStr, tmpClient);
                    tmpBkRet[1] = tmpBkRet[1].substring(4, tmpBkRet[1].length());
                    if (tmpBkRet[0].length() == 0) {
                        byte[] tmpBytesRead = tmpBkRet[1].getBytes();
                        byte[] tmpUnionInfo = new byte[tmpAllBytes.length + tmpBytesRead.length];
                        System.arraycopy(tmpAllBytes, 0, tmpUnionInfo, 0, tmpAllBytes.length);
                        System.arraycopy(tmpBytesRead, 0, tmpUnionInfo, tmpAllBytes.length, tmpBytesRead.length);
                        tmpAllBytes = tmpUnionInfo;
                        WriteBankLogLn("接收：" + tmpBytesRead.length + "字节");
                        if (tmpBkRet[1].length() >= 8) {
                            tmpEachRecStr = tmpBkRet[1].substring(0, 8);
                            WriteBankLogLn( "tmpCount:" + tmpCount + ";  tmpEachRecStr:" + tmpEachRecStr);
                        }
                        /*for (int i = 0; i < tmpEachRecStr.getBytes().length; i++) {
                            if (tmpEachRecStr.getBytes(getCharset())[i] == tmpStrEndFlag.getBytes(getCharset())[i]) {
                                isContinue = false;
                            }
                        }*/
                        if (tmpEachRecStr.getBytes(getCharset())[0] == tmpStrEndFlag.getBytes(getCharset())[0]) {
                            isContinue = false;
                        }
                        WriteBankLogLn("isContinue==" + isContinue);
                    } else {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpBkRet[1];
                        retAts.writeAfterDetail();
                        return retAts;
                    }
                }
                if (tmpEachRecStr == tmpStrEndFlag) {
                    try {
                        tmpBkRet = sendToBank("\0", tmpClient);
                        tmpBkRet[1] = tmpBkRet[1].substring(4, tmpBkRet[1].length());
                        byte[] tmpBytesRead = tmpBkRet[1].getBytes();
                        byte[] tmpUnionInfo = new byte[tmpAllBytes.length + tmpBytesRead.length];
                        System.arraycopy(tmpAllBytes, 0, tmpUnionInfo, 0, tmpAllBytes.length);
                        System.arraycopy(tmpBytesRead, 0, tmpUnionInfo, tmpAllBytes.length, tmpBytesRead.length);
                        tmpAllBytes = tmpUnionInfo;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        retAts.respCode = "-1";
                        retAts.respInfo = ex.toString();
                        WriteBankLogLn(ex);
                    }
                }
                tmpBkRet[1] = new String(tmpAllBytes, getCharset());
                WriteBankLogStep3(tmpBkRet[1]);
                if (tmpBkRet[1] != "-111" && tmpBkRet[1].length() >= 70) {
                    tmpStrRetCode = tmpBkRet[1].substring(tmpBkRet[1].length() - 6, tmpBkRet[1].length());
                    if (tmpStrRetCode == "999999" || tmpStrRetCode.trim().length() < 6) {
                        /*有结果数据详细内容*/
                        int tmpIndexFrom = tmpBkRet[1].indexOf("\n", 0);
                        int tmpIndexTo = tmpIndexFrom;

                        if (tmpIndexFrom > 0 && tmpBkRet[1].length() > (tmpIndexFrom + 1)) {
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            retAts.respCode = "0";

                            int lineCount = 0;
                            while (tmpIndexFrom < tmpBkRet[1].length()) {
                                int tmpChkByteCount = 707;
                                tmpIndexFrom = tmpIndexTo + 1;
                                if (tmpBkRet[1].length() > tmpIndexFrom) {
                                    tmpIndexTo = tmpBkRet[1].indexOf("\n", tmpIndexFrom);
                                    if (tmpIndexTo == -1) {
                                        tmpIndexTo = tmpBkRet[1].length() - 1;
                                    }
                                } else {
                                    break;
                                }
                                String tmpStrEachLine;

                                if (tmpIndexTo > tmpIndexFrom) {
                                    tmpStrEachLine = tmpBkRet[1].substring(tmpIndexFrom, tmpIndexTo - tmpIndexFrom);
                                } else {
                                    break;
                                }
                                lineCount++;

                                byte[] tmpBytesEachLine = tmpStrEachLine.getBytes();
                                if (tmpBytesEachLine.length != tmpChkByteCount) {
                                    WriteBankLogLn("第" + lineCount + "行字节数：" + tmpBytesEachLine.length);
                                    continue;
                                }
                                if (p_reqQryBat.reqHeader.transType == "1998") {
                                    tmpRetDetail.recAct = tmpBkRet[1].substring(0, 25).trim();
                                    tmpRetDetail.recName = tmpBkRet[1].substring(25, 83).trim();
                                } else if (p_reqQryBat.reqHeader.transType == "9198") {
                                    tmpRetDetail.payAct = tmpBkRet[1].substring(0, 25).trim();
                                    tmpRetDetail.payName = tmpBkRet[1].substring(25, 83).trim();
                                }

                                tmpRetDetail.payAmount = tmpBkRet[1].substring(83, 99).trim();
                                tmpRetDetail.memo = tmpBkRet[1].substring(147, 227).trim();
                                int tmpIndex = 0;
                                if (tmpRetDetail.memo.indexOf("Z") >= 0) {
                                    tmpRetDetail.postScript = tmpRetDetail.memo.substring(tmpIndex + 1);
                                }

                                String tmp = tmpBkRet[1].substring(547, 548).trim();
                                if (tmp != "|") {
                                    WriteBankLogLn("第" + lineCount + "行第548个字节不为|");
                                    continue;
                                }
                                tmpRetDetail.result = tmpBkRet[1].substring(548, 549).trim();
                                tmpRetDetail.payInfoCode = tmpBkRet[1].substring(549, 557).trim();
                                tmpRetDetail.memo = tmpBkRet[1].substring(557, 707).trim();

                                if (tmpRetDetail.payInfoCode.equalsIgnoreCase("FFFFFF")) {
                                    tmpRetDetail.payInfoCode = tmpRetDetail.memo;
                                }
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行接口有变更，请联系技术支持人员。";
                        }
                    } else {
                        tmpBkRet[1] = tmpBkRet[1].trim();
                        if (tmpBkRet[1].substring(0, tmpBkRet[1].length() - 6) == tmpStrHead.substring(0, tmpStrHead.length() - 6)) {
                            retAts.payInfoCode = tmpStrRetCode;
                            if (tmpStrRetCode == "900001") {
                                retAts.respInfo = tmpStrRetCode + "-打开文件失败";
                            } else if (tmpStrRetCode == "900008") {
                                retAts.transState = "900008";
                                retAts.respInfo = tmpStrRetCode + "-服务端不能提供文件";
                            } else {
                                retAts.respInfo = tmpStrRetCode;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行接口有变更，请联系技术支持人员。";
                        }
                    }
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.toString();
            WriteBankLogLn(ex);
        } finally {
            if (tmpClient != null) {
                if (tmpClient.socket != null) {
                    tmpClient.socket.close();
                }
                if (tmpClient.tmpOutput != null) {
                    tmpClient.tmpOutput.close();
                }
                if (tmpClient.tmpInput != null) {
                    tmpClient.tmpInput.close();
                }
            }
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}